// src/translator/YoudaoTranslator.ts
import { isWails } from '../../utils/wails';
import { type Translator,type  TranslationResponse } from './Translator';
import {Get} from '../../../wailsjs/go/main/App'
// 有道返回的根结构
interface YoudaoRaw {
  web_trans: {
    "web-translation": Array<{
      "@same"?: string;
      trans?: Array<{ value?: string }>;
    }>;
  };
}

export class YoudaoTranslator implements Translator {
  valid(): boolean {
    return  isWails
  }
  /** 返回翻译器名称 */
  getName(): string {
    return "有道翻译（只能app版使用）";
  }

  /** 翻译英文单词为中文 */
  async translate(text: string, _ = "zh"): Promise<TranslationResponse | null> {
    if (!text.trim()) {
      return null;
    }

    const url = `https://dict.youdao.com/jsonapi?q=${encodeURIComponent(text)}`;

    try {
      // const res = await fetch(url);
      // if (!res.ok) throw new Error(`HTTP ${res.status}`);

      // const json: YoudaoRaw = await res.json();
      const res = await  Get(url);
      const json: YoudaoRaw = JSON.parse(res);

      // 找到 @same="true" 的那一项
      const sameItem = json.web_trans?.["web-translation"]?.find(
        (it) => it["@same"] === "true"
      );
      const values = sameItem?.trans
        ?.map((t) => t.value)
        .filter(Boolean) || [];

      if (!values.length) return null;

      return {
        translation: values.join("，"),
        sourceLang: "en",
      };
    } catch (err) {
      return {
        translation: "",
        sourceLang: "en",
        error: (err as Error).message,
      };
    }
  }
}